package civaid;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

public class JSON {

	private static GsonBuilder gsonBuilder;

	private static String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS";
	private static Charset utf8 = Charset.forName("utf-8");

	private static void init() {
		if (gsonBuilder == null) {
			gsonBuilder = new GsonBuilder();
			gsonBuilder.setDateFormat(DATE_FORMAT);
		}
	}

	public static Object fromJson(Reader reader, Type type) {
		init();
		Gson gson = gsonBuilder.create();
		return gson.fromJson(new JsonReader(reader), type);
	}

	public static void toJson(Object reply, OutputStream outputStream) throws IOException {
		init();
		Gson gson = gsonBuilder.create();
		JsonWriter writer = new JsonWriter(new OutputStreamWriter(outputStream, utf8));
		gson.toJson(reply, reply.getClass(), writer);
		writer.close();

	}

}